package com.dadaguai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dadaguai.common.BusinessException;
import com.dadaguai.common.R;
import com.dadaguai.constants.CaptchaConstants;
import com.dadaguai.constants.ResponseCode;
import com.dadaguai.constants.UserConstants;
import com.dadaguai.domain.UserInfo;
import com.dadaguai.dto.UserInfoDto;
import com.dadaguai.enums.UserIntegralEnum;
import com.dadaguai.service.EmailCodeService;
import com.dadaguai.service.UserInfoService;
import com.dadaguai.mapper.UserInfoMapper;
import com.dadaguai.service.UserIntegralRecordService;
import com.dadaguai.service.UserMessageService;
import com.dadaguai.utils.JwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.util.Date;


/**
 * @author 王半仙
 * @description 针对表【user_info(用户信息)】的数据库操作Service实现
 * @createDate 2023-10-20 11:28:40
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    EmailCodeService emailCodeService;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    UserMessageService userMessageService;

    @Autowired
    UserIntegralRecordService userIntegralRecordService;
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 验证码登录/注册
     *
     * @param user
     * @param session
     * @return
     */
    @Transactional
    @Override
    public R register(UserInfoDto user, HttpSession session) throws BusinessException {
        //1.邮箱验证码校验
        R r = emailCodeService.checkCode(user.getCode(), 1, user.getEmail());
        if ("error".equals(r.getState())) {
            return r;
        }
        //2.校验邮箱是否注册
        // TODO: 2024/1/3 优化校验逻辑，减少数据库查询次数
        Integer count = emailCodeService.queryEmailRegister(user.getEmail());
        if (count > 0) {
            //邮箱已被注册，执行登录逻辑
            return this.loginCheck(user, session, "2");
        }


        //3. 邮箱未注册 封装注册用户数据(读取配置文件，设置用户初始状态)
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user, userInfo);
        userInfo.setTotalIntegral(0);
        userInfo.setCurrentIntegral(0);
        userInfo.setJoinTime(new Date());
        userInfo.setLevel(1);
        userInfo.setStatus(1);
//        生成随机密码
//        byte[] passwordBytes = RandomStringUtils.randomNumeric(6).getBytes();
        byte[] passwordBytes = "111111".getBytes();
        userInfo.setPassword(DigestUtils.md5DigestAsHex(passwordBytes)); // MD5加密
        if (userInfo.getNickName() == null) userInfo.setNickName(user.getEmail()); //默认将邮箱作为昵称

        //4.将用户数据插入数据库
        userInfoMapper.insert(userInfo);

        //5.记录消息
        userMessageService.sendSysMessage(userInfo.getUserId());
        //6.修改用户积分
        userIntegralRecordService.changeUserIntegral(
                userInfo,
                UserIntegralEnum.REGISTER.getType(),
                UserIntegralEnum.REGISTER.getValue()
        );
        // 注册成功，将用户设为登录状态
        return this.userLogin(userInfo, session);
    }

    /**
     * 用户登录校验
     *
     * @param user
     * @param session
     * @param state   1 == 密码登录 ； 2 == 验证码登录
     * @return
     */
    @Override
    public R loginCheck(UserInfoDto user, HttpSession session, String state) {
        UserInfo userInfo = userInfoMapper.selectByEmail(user.getEmail());
        // 密码校验
        if (state.equals("1")) {
            if (userInfo == null || !userInfo.getPassword().equals(user.getPassword())) {
                return R.error("用户名或密码错误", ResponseCode.USER_PARAM_ERROR);
            }
        }
        // 账号状态校验
        if (userInfo.getStatus() == 0) return R.error("该账号已被禁用", ResponseCode.USER_DISABLED);
        // 校验通过
        return userLogin(userInfo, session);
    }

    /**
     * 用户登录成功，更新用户相关状态
     *
     * @param user
     * @param session
     * @return
     */
    public R userLogin(UserInfo user, HttpSession session) {
        // 更新用户登陆时间
        user.setLastLoginTime(new Date());
        //保存用户信息到session
        UserInfoDto userInfoDto = new UserInfoDto();
        BeanUtils.copyProperties(user, userInfoDto);
        session.setAttribute(UserConstants.USER_INFO_KEY, userInfoDto);
        session.setAttribute(UserConstants.USER_ID_KEY, userInfoDto.getUserId());
        userInfoDto.setPassword("");
        //生成token
        String token = JwtUtil.sign(user.getUserId());
        //  返回用户数据和token
        return R.success(userInfoDto).add("token", token);
    }

    /**
     * 修改密码
     *
     * @param email    邮箱地址
     * @param password 新密码
     * @param code     邮箱验证码
     * @return
     */
    @Override
    public R changePassword(String email, String password, String code) {
        // 校验验证码
        R r = emailCodeService.checkCode(code, CaptchaConstants.EMAIL_CODE, email);
        if (r.getState().equals("error")) return r;
        //修改密码
        Integer count = userInfoMapper.updatePassword(email, DigestUtils.md5DigestAsHex(password.getBytes()));
        if (count == 0) return R.error("操作失败", ResponseCode.USER_HANDLE_ERROR);
        return R.success("操作成功");

    }

    /**
     * 修改用户信息
     *
     * @param user    修改参数
     * @param session
     * @return
     */
    @Override
    public R setProfile(UserInfoDto user, HttpSession session) {
        String userId = (String) session.getAttribute(UserConstants.USER_ID_KEY);
        if (!userId.equals(user.getUserId())) {
            return R.error("请求参数错误", ResponseCode.PARAM_MISS_ERROR);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setNickName(user.getNickName());
        userInfo.setBirth(user.getBirth());
        userInfo.setSex(user.getSex());
        userInfo.setIconUrl(user.getIconUrl());
        userInfo.setPersonDescription(user.getPersonDescription());
        boolean result = this.updateById(userInfo);
        if (!result) {
            return R.error("数据库异常", ResponseCode.DATA_UPDATE_ERROR);
        }
        return getUserInfo(userId);
    }

    /**
     * 查询用户信息
     *
     * @param id
     * @return
     */
    @Override
    public R getUserInfo(String id) {
        UserInfo user = userInfoMapper.selectById(id);
        if (user == null) return R.error("用户不存在", ResponseCode.USER_HANDLE_ERROR);
        UserInfoDto userInfoDto = new UserInfoDto();
        BeanUtils.copyProperties(user, userInfoDto);
        userInfoDto.setPassword("");
        return R.success(userInfoDto);
    }


}




